import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

data = pd.read_csv("nba_2017_nba_players_with_salary.csv")


# # 1.数据相关性分析
# # 分析指标 'RPM' 与其它指标 'AGE', 'SALARY_MILLIONS', 'ORB', 'DRB', 'TRB' 的关系
# data1 = data.loc[:, ['RPM', 'AGE', 'SALARY_MILLIONS', 'ORB', 'DRB', 'TRB']]
# # 列相关性分析函数 corr()
# data1_corr = data1.corr()
# """
#                       RPM       AGE  ...       DRB       TRB
# RPM              1.000000  0.175820  ...  0.623515  0.587853
# AGE              0.175820  1.000000  ...  0.088859  0.062064
# SALARY_MILLIONS  0.477542  0.353312  ...  0.531569  0.482088
# ORB              0.388764 -0.015752  ...  0.731345  0.861103
# DRB              0.623515  0.088859  ...  1.000000  0.976244
# TRB              0.587853  0.062064  ...  0.976244  1.000000
# """
# print(data1_corr)
# # 绘制热力图
# plt.figure(figsize=(10, 10), dpi=80)
# # annot 代表是否在热力图的每个网格上显示相关系数
# # 在热力图中，颜色越浅相关性越高
# sns.heatmap(data1_corr, square=True, linewidths=0.02, annot=True)
# plt.show()

# # 2.球员薪水'Salary'，效率值'RPM'与年龄'AGE'三者的单变量分布
# sns.set_style("darkgrid")  # 设置面板风格
# plt.figure(figsize=(10, 10), dpi=80)
# plt.subplot(3, 1, 1)  # 要在画板上展示3个子图，现在要画第一列第一行的图
# sns.histplot(data=data.loc[:, "SALARY_MILLIONS"], kde=True)
# plt.xticks(np.linspace(0, 40, 9))  # 9个间隔，10个数
# plt.xlabel("salary")
#
#
# plt.subplot(3, 1, 2)  # 要在画板上展示3个子图，现在要画第一列第二行的图
# sns.histplot(data=data.loc[:, "RPM"], kde=True)
# plt.xticks(np.linspace(-10, 10, 9))  # 9个间隔，10个数
# plt.xlabel("RPM")
#
#
# plt.subplot(3, 1, 3)  # 要在画板上展示3个子图，现在要画第一列第三行的图
# sns.histplot(data=data.loc[:, "AGE"], kde=True)
# plt.xticks(np.linspace(20, 40, 11))  # 11个间隔，12个数
# plt.xlabel("AGE")
# plt.show()

# # 3.查看薪水和年龄之间的相关性，密度图越密集相关性越高
# sns.set_style("darkgrid")  # 设置面板风格
# plt.figure(figsize=(10, 10), dpi=80)
# sns.kdeplot(x="SALARY_MILLIONS", y="AGE", data=data)
# plt.xlabel("SALARY_MILLIONS")
# plt.ylabel("AGE")
# plt.show()

# # 4. 'AGE', 'SALARY_MILLIONS', 'ORB', 'DRB', 'TRB'的关系
# sns.set_style("darkgrid")  # 设置面板风格
# plt.figure(figsize=(10, 10), dpi=80)
# df = data.loc[:, ['AGE', 'SALARY_MILLIONS', 'ORB', 'DRB', 'TRB']]
# sns.pairplot(df)  # 相关性展示，主对角线为自身分布展示
# plt.show()

# 5. 衍生的可视化实践
def age_cut(df):
    """年龄划分"""
    if df.AGE <= 24:
        return "young"
    elif df.AGE >= 30:
        return "old"
    else:
        return "best"


# # 使用apply对年龄进行划分
# data["age_cut"] = data.apply(lambda x: age_cut(x), axis=1)
# # # 方便计数
# data["cut"] = 1
# # 基于年龄段对球员薪水和效率值进行分析
# sns.set_style("darkgrid")
# plt.figure(figsize=(10, 10), dpi=80)
# plt.title("RPM and Salary")
#
# x1 = data.query("age_cut =='old'").SALARY_MILLIONS
# y1 = data.loc[data.age_cut == "old"].RPM
# plt.plot(x1, y1, "^", label="old")
# print("*"*100)
# print(data.query("age_cut =='old'"))
# print(data.loc[data.age_cut == "old"])
# print(data[data.age_cut == "old"])
# print("*"*100)
# x2 = data.loc[data.age_cut == "best"].SALARY_MILLIONS
# y2 = data.loc[data.age_cut == "best"].RPM
# plt.plot(x2, y2, "^", label="best")
#
# x3 = data.loc[data.age_cut == "young"].SALARY_MILLIONS
# y3 = data.loc[data.age_cut == "young"].RPM
# plt.plot(x3, y3, ".", label="young")
# plt.legend()
# plt.show()

# 6. 球队平均薪资排行，agg 自定义聚合函数，实现多列同时聚合
data_team = data.groupby(by="TEAM").agg({"SALARY_MILLIONS": np.mean})
# print(data_team.head())
# data_team2 = data.groupby(by="TEAM")["SALARY_MILLIONS"].mean()
# print(data_team2.head())
# """
# TEAM
# ATL            6.689167
# ATL/CLE        5.040000
# ATL/PHI/OKC    8.400000
# BKN            5.704545
# BKN/WSH        4.910000
# """
# data_team = data_team.sort_values(by="SALARY_MILLIONS", ascending=False)
# print(data_team.head())

# 按照分球队分年龄段，上榜球员降序排列，如上榜球员数相同，则按效率值降序排列。
# data_rpm = data.groupby(by=["TEAM", "age_cut"]).agg({"SALARY_MILLIONS": np.mean, \
#                                                      "RPM": np.mean, \
#                                                      "PLAYER": np.size})
# print(data_rpm)
"""
                     SALARY_MILLIONS       RPM  PLAYER
TEAM        age_cut                                   
ATL         best            4.678000 -1.768000       5
            old            12.775000  0.982500       4
            young           1.926667 -3.076667       3
ATL/CLE     old             5.040000 -2.485000       2
ATL/PHI/OKC best            8.400000  1.720000       1
...                              ...       ...     ...
UTAH        old             8.666667 -0.033333       3
            young           2.452500  0.025000       4
WSH         best            7.052500 -0.462500       4
            old            10.980000  0.093333       3
            young          12.755000 -1.495000       2
"""
# data_rpm.sort_values(by=["PLAYER", "RPM"], ascending=False)

# 7. 利用箱线图和小提琴图进行数据分析,对'GS', 'CLE', 'SA', 'LAC', 'OKC', 'UTAH', 'CHA', 'TOR', 'NO', 'BOS'队伍的 "AGE" 进行分布分析
# 拿到data中的队伍在'GS', 'CLE', 'SA', 'LAC', 'OKC', 'UTAH', 'CHA', 'TOR', 'NO', 'BOS'内的数据
teams = data.query("TEAM in ['GS', 'CLE', 'SA', 'LAC', 'OKC', 'UTAH', 'CHA', 'TOR', 'NO', 'BOS']")
sns.set_style("darkgrid")
plt.figure(figsize=(15, 10), dpi=80)
plt.title("AGE Analysis")
sns.boxplot(x="TEAM", y="AGE", data=teams)
plt.show()
sns.violinplot(x="TEAM", y="AGE", data=teams)
plt.show()
